from datetime import datetime
import pandas as pd
import numpy as np

def CalChipDistribution(stockCode, date):
    df = pd.read_csv('/Users/yeren/Downloads/stock/' + stockCode + '.csv', encoding='gbk', skiprows=1, parse_dates=['交易日期'])
    date = datetime.strptime(str(date), '%Y/%s/%d')
    df = df[df['交易日期'] <= date]

    # 计算涨跌幅
    df['涨跌幅'] = df['收盘价']/df['前收盘价'] - 1

    # 计算复权价: 计算所有因子当中用到的价格，都使用复权价
    df['复权因子'] = (1 + df['涨跌幅']).cumprod()
    df['收盘价_复权'] = df['复权因子'] * (df.iloc[0]['收盘价'] / df.iloc[0]['复权因子'])
    df['均价'] = df['成交额'] / df['成交量']
    df['均价_复权'] = np.round(df['收盘价_复权'] * df['均价'] / df['收盘价'], 2)

    # 计算每日股票换换手率
    df['换手率'] = df['成交额'] / df['流通市值']

    df = df[['交易日期', '均价_复权', '前收盘价', '换手率']]

    # 按照日期排列
    df = df.sort_values(by='交易日期', ascending=True).reset_index(drop=True)

    # 获取一下总共交易了多少天
    rows = df.shape[0]

    # 创建一个df来存放分布
    chips = pd.DataFrame(columns={'均价_复权':'', '比例': '', '盈亏': ''})

    # 获取发行价
    issuePrice = df['前收盘价'][0]

    # 把发行价添加筹码分布里面
    # temp=pd.DataFrame(columns={'均价_复权':issuePrice, '比例': 1.0, '盈亏':'g'}, index=['0'])
    temp = {'均价_复权':issuePrice, '比例': 1.0, '盈亏':'g'}
    chips = chips.append(temp, ignore_index=True)

    for i in range(0, rows):
        # 获取均价
        price = df['均价_复权'][i]
        # 如果这个价格不在已有的筹码里面
        if price not in chips['均价_复权'].tolist():
            # 添加到筹码分布中
            temp = {'均价_复权': price, '比例': 0.0, '盈亏':'g'}
            chips = chips.append(temp, ignor_index=True)
            # 其他价格的筹码比例 x (1-换手率)
            chips['比例'] = chips['比例'] * (1 - df['换手率'][i])
            priceIndex = chips.loc[chips['均价_复权'] == price].index
            # 新价格的筹码比例等于换手率
            chips['比例'][priceIndex] = df['换手率'][i]
        else:
            # 所有价格的筹码比例 X (1 - 换手率)
            chips['比例'] = chips['比例'] * (1 - df['换手率'][i])
            priceIndex = chips.loc[chips['均价_复权'] == price].index
            # 当日价格的筹码在之前变动的基础上加上换手率
            chips['比例'][priceIndex] = df['换手率'][i] + chips['比例'][priceIndex]

    # 按照价格排序
    chips.sort_values['均价_复权', inplace=True)
    currentPrice = df['均价_复权'][rows - 1]
    # 价格高于当前价格的记为亏损
    chips.loc[chips['均价_复权'] >= currentPrice, '盈亏'] = 'g'
    chips.loc[chips['均价_复权'] < currentPrice, '盈亏'] = 'r'
    chips.reset_index(inplace=True, drop=True)
    return chips





